package com.yang.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yang.domain.*;
import com.yang.handler.UserThreadLocal;
import com.yang.service.ChatFriendRelService;
import com.yang.service.GoodsService;
import com.yang.service.OrderGoodsDetailsService;
import com.yang.service.OrderService;
import com.yang.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Controller
 *
 * @author 不是菜鸡爱编程
 * @date 2024-02-18
 */
@Slf4j
@RestController
@RequestMapping("/orders")
@Api(tags = "订单模块", value = "订单Controller")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderGoodsDetailsService orderGoodsDetailsService;
    @Autowired
    private ChatFriendRelService chatFriendRelService;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/list")
    public R list(Order order, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        User user = UserThreadLocal.get();
        if (user.getIsAdmin() != 2) {
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                    .eq(ObjUtil.isNotEmpty(order.getId()), Order::getId, order.getId())
                    .eq(ObjUtil.isNotEmpty(order.getUserId()), Order::getUserId, order.getUserId())
                    .eq(ObjUtil.isNotEmpty(order.getTotalPrice()), Order::getTotalPrice, order.getTotalPrice())
                    .eq(ObjUtil.isNotEmpty(order.getDelFlag()), Order::getDelFlag, order.getDelFlag());
            // 如果是普通用户，则只能查询到逻辑删除列为0的数据【且只能查询到自己的车辆信息】
            wrapper.eq(user.getIsAdmin() != 0, Order::getDelFlag, 0)
                    // 司机只能查看自己的订单
                    .eq(user.getIsAdmin() == 1, Order::getUserId, user.getId());
            // 查询到全部车辆信息
            IPage<Order> page = orderService.page(new Page<>(pageNum, pageSize), wrapper);
            return R.ok().setData(page);
        }
        // 货主能查看到司机的订单，但是只能查看到自己货源的部分
        MPJLambdaWrapper<Goods> joinWrapper = new MPJLambdaWrapper<Goods>()
                .selectAll(Order.class)
                .distinct()
                .leftJoin(OrderGoodsDetails.class, OrderGoodsDetails::getGoodsId, Goods::getId)
                .leftJoin(Order.class, Order::getId, OrderGoodsDetails::getOrderId)
                .in(Goods::getDelFlag, 1)
                .eq(Goods::getCreateBy, user.getId())
                .groupBy(Order::getId);
        IPage<Order> page = new Page<>(pageNum, pageSize);
        goodsService.selectJoinListPage(page, Order.class, joinWrapper);
        return R.ok().setData(page);
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        MPJLambdaWrapper<Order> wrapper = new MPJLambdaWrapper<Order>()
                //查询user表全部字段
                .selectAll(Goods.class)
                .leftJoin(OrderGoodsDetails.class, OrderGoodsDetails::getOrderId, Order::getId)
                .leftJoin(Goods.class, Goods::getId, OrderGoodsDetails::getGoodsId)
                .eq(Order::getId, id)
                .groupBy(Goods::getId);
        List<Goods> goods = orderService.selectJoinList(Goods.class, wrapper);
        User user = UserThreadLocal.get();
        Map<String, Object> map = new HashMap<>();
        Object driver =  orderService.selectJoinOne(User.class, new MPJLambdaWrapper<Order>()
                .selectAll(User.class)
                .leftJoin(User.class, User::getId, Order::getUserId)
                .eq(Order::getId, id)
                .groupBy(Goods::getId));
        if (user.getIsAdmin() == 2) {
            // 如果是货主，需要查看到订单司机信息
            List<Goods> collect = goods.stream().filter(item -> user.getId().equals(item.getCreateBy())).collect(Collectors.toList());
            map.put("goods", collect);
            map.put("driver",driver);
            return R.ok().setData(map);
        }
        if (user.getIsAdmin() == 1) {
            map.put("driver",driver);
        }else{
            map.put("driver", null);
        }
        map.put("goods", goods);
        return R.ok().setData(map);
    }

    /**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PostMapping
    public R add(@RequestBody Integer[] ids) {
        User user = UserThreadLocal.get();
        List<Goods> goodsList = goodsService.list(new LambdaQueryWrapper<Goods>()
                .in(ids.length > 0, Goods::getId, Arrays.asList(ids))
                .eq(user.getIsAdmin() != 0, Goods::getDelFlag, 0));
        Order order = new Order();
        long snowflakeNextId = IdUtil.getSnowflakeNextId();
        String snowflake = String.valueOf(snowflakeNextId);
        order.setId(snowflake);
        order.setUserId(user.getId());
        order.setGoodsList(goodsList);
        Double totalPrice = goodsList.stream().map(Goods::getPrice).reduce(Double::sum).orElse(0.0);
        order.setTotalPrice(totalPrice);
        order.setCreateBy(user.getId());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateBy(user.getId());
        order.setUpdateTime(LocalDateTime.now());
        order.setDelFlag(0);
        ArrayList<OrderGoodsDetails> orderGoodsDetails = new ArrayList<>();
        for (Integer id : ids) {
            orderGoodsDetails.add(new OrderGoodsDetails(snowflake, id));
        }
        // 删除货源
        goodsService.update(new LambdaUpdateWrapper<Goods>()
                .in(Goods::getId, Arrays.asList(ids))
                .set(Goods::getDelFlag, 1));
        orderGoodsDetailsService.saveBatch(orderGoodsDetails);
        orderService.save(order);
        // 新增好友关系
        List<Integer> goodsOwnerUserIdList = goodsList.stream().map(Goods::getCreateBy).distinct().collect(Collectors.toList());
        List<ChatFriendRel> chatFriendRels = new ArrayList<>();
        for (Integer goodsOwnerUserId : goodsOwnerUserIdList) {
            chatFriendRels.add(new ChatFriendRel(user.getId(), goodsOwnerUserId));
            chatFriendRels.add(new ChatFriendRel(goodsOwnerUserId, user.getId()));
        }
        chatFriendRelService.saveBatch(chatFriendRels);
        return R.ok();
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PutMapping
    public R edit(@RequestBody Order order) {
        return R.ok().setData(orderService.update(order, new LambdaQueryWrapper<Order>()
                .eq(Order::getId, order.getId())));
    }

    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.ok().setData(orderService.update(null, new LambdaUpdateWrapper<Order>()
                .set(Order::getDelFlag, 1)
                .in(Order::getId, Arrays.asList(ids))));
    }
}
